package com.three.http;

import com.alibaba.druid.support.json.JSONUtils;
import com.three.service.AlipayService;
import com.three.utils.LogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import java.util.Map;
import java.util.stream.Collectors;

import static com.three.constant.ShopConstants.*;

/**
 * 供第三方充值回调
 */
@RestController
public class ShopCallBackController {
    @Autowired
    private AlipayService alipayService;
    @RequestMapping(value = "/alipay/notify",method = RequestMethod.POST)
    public String alipay_callBack(HttpServletRequest request){
        LogUtils.SHOP.warn(JSONUtils.toJSONString(request.getParameterMap()));
        LogUtils.Console.warn("测试：{}",JSONUtils.toJSONString(request.getParameterMap()));
        //获取支付宝POST过来反馈信息
        Map<String,String> params=request.getParameterMap().entrySet().stream()
                .collect(Collectors.toMap(
                        entry->entry.getKey(),
                        entry->String.join(",",entry.getValue())
                ));
        if(!alipayService.check(params)){
            LogUtils.SHOP.warn("阿里支付，验签失败，信息：{}",params);
            return FAILURE;
        }
        String trade_status=params.get("trade_status");
        String response;
        switch (trade_status){
            case WAIT_BUYER_PAY://交易创建，等待买家付款
                response = SUCCESS;//不处理
                break;
            case TRADE_CLOSED://未付款交易超时关闭，或支付完成后全额退款
                response = SUCCESS;//不支持退款,不处理
                break;
            case TRADE_SUCCESS://交易支付成功
                response = alipayService.handle(params);
                break;
            case TRADE_FINISHED://交易结束，不可退款
                response = alipayService.handle(params);
                break;
            default:
                response = SUCCESS;//不处理
                break;
        }
        return response;
    }


}
